<?php

namespace app\api\model\service;

use think\Exception;
use think\Model;
class RefundOrder extends Model
{
    // 表名
    protected $name = 'service_refund_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';




    public static function applyRefund($params)
    {
        $order = Order::where(['user_id'=>$params['user_id'],'id'=>$params['id'],'status'=>['>',0]])->field('id,user_id,is_service,payprice,to_shop,skill_id,shop_id,status,payprice')->find();
        if(!$order)
        {
            throw new Exception('当前订单无法申请退款');
        }
        if($order['is_service'] > 0)
        {
            throw new Exception('请勿重复申请退款');
        }
        if($order['payprice'] < $params['refund_price'] || $params['refund_price']<0)
        {
            throw new Exception('当前退款金额不符');
        }
        $refundReason = RefundReason::where(['id'=>$params['refund_reason_id']])->value('name');
        $params['refund_reason'] = $refundReason;
        $params['order_id'] = $params['id'];
        unset($params['id']);
        $refundOrder = new RefundOrder($params);
        $refundOrder->allowField(true)->save();

        if($order['is_service'] != 1)
        {
            Order::where(['id'=>$order['id']])->update(['is_service'=>1]);
        }

        OrderLog::create(['order_id'=>$order['id'],'user_id'=>$order['user_id'],'type'=>8,'content'=>'订单已申请退款']);
        if($order['skill_id'])
        {
            $skillOpenid = UserInfo::getOpenid($order['skill_id'],1);
            Order::createOrderTemplateParams(['id'=>$order['id'],'user_id'=>$order['user_id'],'to_shop'=>$order['to_shop'],'type'=>1,'templateAttr'=>'skill_sales_template','openid'=>$skillOpenid]);
        }
        if($order['shop_id'])
        {
            $shopOpenid = UserInfo::getOpenid($order['shop_id'],2);
            Order::createOrderTemplateParams(['id'=>$order['id'],'user_id'=>$order['user_id'],'to_shop'=>$order['to_shop'],'type'=>2,'templateAttr'=>'shop_sales_template','openid'=>$shopOpenid]);
        }
        return $order;
    }

    public static function cancelRefundOrder($refundOrder)
    {
        self::where('order_id',$refundOrder['order_id'])->update(['state'=>-2]);
        Order::where('id',$refundOrder['order_id'])->update(['is_service'=>0]);
        OrderLog::create(['order_id'=>$refundOrder['order_id'],'user_id'=>$refundOrder['user_id'],'type'=>17,'content'=>'用户取消申请退款']);
        return true;
    }


}
